const axios = require('axios');
import qs from 'qs';
// import JSEncrypt from 'jsencrypt';

// //rsa公钥
// const key = `-----BEGIN PUBLIC KEY-----${window.CAKE}-----END PUBLIC KEY-----`

// //rsa
// const encrypt = new JSEncrypt();
// encrypt.setPublicKey(key);

// /**
//  * ras加密
//  * 由于这个库每次最多117个字符串加密，所以要分割字符串加密
//  * @param {String} params
//  */
// function encode(params){
//   let rs = params

//   //配置文件是否开启加密
//   if(process.env.rsa){
//     rs = [];
//     let strs = params.match(/.{1,117}/g);
//     strs.forEach(item=>{
//       rs.push(encrypt.encrypt(item));
//     })
//   }

//   return rs;
// }
export default ({ app,route }, inject) => {
  let lang = 'zh-cn';
  let uuid = '';
  let os = 'web';
  let version = window.API_VERSION || '';
  let $http = axios.create({
      baseURL: window.BASE_URL,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
      },
      params:{
        os,
      },
      transformRequest: [function(data, headers) {
        let token = app.store.getters.getToken;
        let uid = app.store.getters.getUid;
        return qs.stringify({post_data:JSON.stringify(Object.assign({
          token,
          uid,
          lang,
          uuid,
          version,
          os
        },data))});
      }]
  });

  $http.interceptors.response.use(function(response) {
      if(!!response.data.token){
        localStorage.setItem('token',response.data.token);
      }
      if (response.data.code === -10001) {
        app.store.dispatch('LOGOUT');
        //登录注册页面不处理
        let flag = true;
        if(route.matched[0]){
          let path = route.matched[0].path;
          if(['login','register'].find(item=>`/${item}`===path)){
            flag = false;
          }
        }
        if(flag){
          if(app.$tools.isLema){
            if(app.$tools.isIOS){
              console.log('ios goLogin true');
              window.webkit.messageHandlers.goLogin.postMessage(true);
            }else if(app.$tools.isAndroid){
              console.log('android goLogin');
              window.JSInterface2Java.goLogin();
            }
          }else{
            app.$alert('您的账号已在其他设备进行登录').then(()=>{
              app.router.push('/login');
            }).catch(e=>{
              app.router.push('/login');
            })
          }
        }

      } else{
        //参数错误且uid或token不存在时，跳到登录页面
        if(response.data.code === -10000 && (!localStorage.getItem('token') || !localStorage.getItem('uid'))){
          app.$alert('您的账号已在其他设备进行登录').then(()=>{
            app.router.push('/login');
          }).catch(e=>{
            app.router.push('/login');
          })
        }
        return response;
      }
  }, function(error) {
      // Do something with response error
      return Promise.reject(error);
  });

  inject('axios',$http);
}
